package com.ruoyi.system.service.impl;

import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Certificate;
import com.ruoyi.common.core.domain.entity.IssuerUnit;
import com.ruoyi.common.core.domain.model.UploadCerBody;
import com.ruoyi.common.utils.Base64Utils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.jm.CertStruct;
import com.ruoyi.common.utils.jm.CertificateInfo;
import com.ruoyi.common.utils.jm.CertificateUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.IIssuerUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CertificateMapper;
import com.ruoyi.system.service.ICertificateService;
import com.ruoyi.common.utils.PFXUtil;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Decode;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Encode;
import static com.ruoyi.common.utils.jm.RSACrypto.CreateUserRSAPfx;
import static com.ruoyi.common.utils.jm.SM2Crypto.CreateUserSM2Pfx;
/**
 * 证书信息Service业务层处理
 *
 * @author ess
 * @date 2021-10-18
 */
@Service
public class CertificateServiceImpl implements ICertificateService
{
    @Autowired
    private CertificateMapper certificateMapper;

    @Autowired
    private IIssuerUnitService iIssuerUnitService;



    /**
     * 查询证书信息
     *
     * @param certId 证书信息主键
     * @return 证书信息
     */
    @Override
    public Certificate selectCertificateByCertId(String certId)
    {
        return certificateMapper.selectCertificateByCertId(certId);
    }

    /**
     * 查询证书信息列表
     *
     * @param certificate 证书信息
     * @return 证书信息
     */
    @Override
    public List<Certificate> selectCertificateList(Certificate certificate)
    {
        return certificateMapper.selectCertificateList(certificate);
    }

    /**
     * 新增证书信息
     *
     * @param certificate 证书信息
     * @return 结果
     */
    @Override
    public int insertCertificate(Certificate certificate)
    {
        return certificateMapper.insertCertificate(certificate);
    }

    /**
     * 修改证书信息
     *
     * @param certificate 证书信息
     * @return 结果
     */
    @Override
    public int updateCertificate(Certificate certificate)
    {
        return certificateMapper.updateCertificate(certificate);
    }

    /**
     * 批量删除证书信息
     *
     * @param certIds 需要删除的证书信息主键
     * @return 结果
     */
    @Override
    public int deleteCertificateByCertIds(String[] certIds)
    {
        return certificateMapper.deleteCertificateByCertIds(certIds);
    }

    /**
     * 删除证书信息信息
     *
     * @param certId 证书信息主键
     * @return 结果
     */
    @Override
    public int deleteCertificateByCertId(String certId)
    {
        return certificateMapper.deleteCertificateByCertId(certId);
    }

    /**
     * 系统生成证书
     * @param certificate 证书信息
     * @return 结果
     */
    @Override
    public AjaxResult createCertificate(Certificate certificate) {
        certificate.setCountry("CN");
        certificate.setState(1L);
        certificate.setCertState(4L);
        IssuerUnit issuerUnit = new IssuerUnit();
        String algorithm = certificate.getAlgorithm();
        issuerUnit.setAlgorithm(algorithm);
        List<IssuerUnit> issuerUnits = iIssuerUnitService.selectIssuerUnitList(issuerUnit);
        issuerUnit  = issuerUnits.get(0);
        CertStruct cert = null;
        try {
            if ("SHA1withRSA".equals(algorithm)){
                cert = CreateUserRSAPfx(certificate.getProvince(),certificate.getCity(),certificate.getUnit(),
                        certificate.getDepartment(),certificate.getCertName(),ESSGetBase64Decode(issuerUnit.getIssuerUnitRoot()),
                        ESSGetBase64Decode(issuerUnit.getIssuerUnitPfx()),issuerUnit.getPfxPwd());
            }else{
                cert = CreateUserSM2Pfx(certificate.getProvince(),certificate.getCity(),certificate.getUnit(),
                        certificate.getDepartment(),certificate.getCertName(),
                        ESSGetBase64Decode(issuerUnit.getIssuerUnitRoot()),
                        ESSGetBase64Decode(issuerUnit.getIssuerUnitPfx()),
                        issuerUnit.getPfxPwd());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("证书申请异常");
        }
        if (cert!=null){
            certificate.setPfxBase64(ESSGetBase64Encode(cert.bPfx));
            certificate.setCerBase64(ESSGetBase64Encode(cert.bCert));
            certificate.setCertPsw(cert.sPin);
        }else{
            return AjaxResult.error("证书数据为空");
        }
        if (insertCertificate(certificate)==1){
            return AjaxResult.success("证书申请成功");
        }
        return AjaxResult.error("证书数据插入失败");
    }

    @Override
    public AjaxResult upLoadCertificate(UploadCerBody uploadCerBody,String commonUrl) {
        boolean result = true;
        CertificateInfo certificateInfo = new CertificateInfo();
        //验证证书是否被信任
//        result = issuerUnitService.VerifyCert(certBase64);
        try {
            if (result) {
                Certificate certificate = new Certificate();
                //根据上传的类型设置信息
                if (!StringUtils.isEmpty(uploadCerBody.getCertPath()) && StringUtils.isEmpty(uploadCerBody.getPfxPath()) || StringUtils.isEmpty(uploadCerBody.getPassword())) {

                    String certBase64 = Base64Utils.encodeBase64File(commonUrl + uploadCerBody.getCertPath());

                    //上传的是cer证书
                    certificateInfo = CertificateUtil.GetCertInfoFromCer(ESSGetBase64Decode(certBase64));
                    certificate.setCerBase64(certBase64);

                } else if (StringUtils.isEmpty(uploadCerBody.getCertPath()) && !StringUtils.isEmpty(uploadCerBody.getPfxPath()) || !StringUtils.isEmpty(uploadCerBody.getPassword())) {

                    String pfxBase64 = Base64Utils.encodeBase64File(commonUrl + uploadCerBody.getPfxPath());

                    certificateInfo = CertificateUtil.GetCertInfoFromPfx(ESSGetBase64Decode(pfxBase64), uploadCerBody.getPassword());
                    String certBase64PFX = ESSGetBase64Encode(CertificateUtil.GetCertFromPfx(ESSGetBase64Decode(pfxBase64), uploadCerBody.getPassword()));
                    certificate.setPfxBase64(pfxBase64);
                    certificate.setCerBase64(certBase64PFX);
                    certificate.setCertPsw(uploadCerBody.getPassword());
                }
                else if(!StringUtils.isEmpty(uploadCerBody.getUkCert())){
                    //上传的是ukeyCer证书  先认为是Base64格式的 20220510
                    certificateInfo = CertificateUtil.GetCertInfoFromCer(ESSGetBase64Decode(uploadCerBody.getUkCert()));
                    certificate.setCerBase64(uploadCerBody.getUkCert());
                }
                else {
                    return AjaxResult.error("证书数据有错，请检查");
                }
                certificate.setCertId(IdUtils.simpleUUID());
                certificate.setAlgorithm(certificateInfo.getsSignAlgName());
                certificate.setStartTime(certificateInfo.getsTimeBegin());
                certificate.setEndTime(certificateInfo.getsTimeEnd());
                certificate.setIssuer(certificateInfo.getsIssuerInfo());
                certificate.setCertName(certificateInfo.getsUserInfo());
                certificate.setState(1L);
                int result1 = certificateMapper.insertCertificate(certificate);
                if (result1 == 1) {
                    return AjaxResult.success(certificate.getCertId());
                }
            } else {
                return AjaxResult.error("证书的颁发者不在可信任列表中，不可使用");
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error("未知错误，请联系管理员");
    }
}
